package com.demo.service.schedule;

import com.demo.service.config.MqttClientConnection;
import com.demo.service.properties.MqttProperties;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class MonitorMessage {

    @Autowired
    private MqttClientConnection mqttClientConnection;

    @Autowired
    private MqttProperties mqttProperties;

    @Autowired
    private MqttConnectOptions mqttConnectOptions;


    /**
     * 使用@PostConstruct注解表示在Bean初始化完成后执行该方法
     * 订阅 MQTT 消息
     */
    @PostConstruct
    public void getSubscribemqttMessage() {
        try {
            // 获取订阅 MQTT 客户端
            MqttClient subscribemqttClient = mqttClientConnection.getSubscribemqttClient();
            subscribemqttClient.setCallback(new MqttCallback() {

                public void connectionLost(Throwable cause) {
                    // 连接丢失
                    log.info("Connection lost: {}", cause.getMessage());
                }

                public void messageArrived(String topic, MqttMessage message) {
                    // 接收到消息
                    log.info("Topic: {}", topic);
                    log.info("QoS: {}", message.getQos());
                    log.info("Message content: {}", new String(message.getPayload()));
                }

                public void deliveryComplete(IMqttDeliveryToken token) {
                    // 消息传递完成
                    log.info("Delivery complete: {}", token.isComplete());
                }

            });
            // 连接并订阅 MQTT 主题
            subscribemqttClient.connect(mqttConnectOptions);
            subscribemqttClient.subscribe(mqttProperties.getTopic(), mqttProperties.getQos());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
